Your First AI application

Going forward, AI algorithms will be incorporated into more and more everyday applications. For example, you might want to include an image classifier in a smart phone app. To do this, you'd use a deep learning model trained on hundreds of thousands of images as part of the overall application architecture. A large part of software development in the future will be using these types of models as common parts of applications.

In this project, you'll train an image classifier to recognize different species of flowers. You can imagine using something like this in a phone app that tells you the name of the flower your camera is looking at. In practice you'd train this classifier, then export it for use in your application. We'll be using this dataset from Oxford of 102 flower categories, you can see a few examples below.

The project is broken down into multiple steps:

  • Load the image dataset and create a pipeline.
  • Build and Train an image classifier on this dataset.
  • Use your trained model to perform inference on flower images.

We'll lead you through each part which you'll implement in Python.

When you've completed this project, you'll have an application that can be trained on any set of labeled images. Here your network will be learning about flowers and end up as a command line application. But, what you do with your new skills depends on your imagination and effort in building a dataset. For example, imagine an app where you take a picture of a car, it tells you what the make and model is, then looks up information about it. Go build your own dataset and make something new.

Install Datasets and Upgrade TensorFlow

To ensure we can download the latest version of the oxford_flowers102 dataset, let's first install both tensorflow-datasets and tfds-nightly.

  • tensorflow-datasets is the stable version that is released on a cadence of every few months
  • tfds-nightly is released every day and has the latest version of the datasets

We'll also upgrade TensorFlow to ensure we have a version that is compatible with the latest version of the dataset.

In [1]:
%pip --no-cache-dir install tensorflow-datasets --user
%pip --no-cache-dir install tfds-nightly --user
%pip --no-cache-dir install --upgrade tensorflow --user
%pip --no-cache-dir install --upgrade pandas --user
Requirement already satisfied: tensorflow-datasets in /opt/conda/lib/python3.7/site-packages (1.2.0)
Requirement already satisfied: protobuf>=3.6.1 in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (3.11.2)
Requirement already satisfied: wrapt in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (1.11.2)
Requirement already satisfied: six in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (1.12.0)
Requirement already satisfied: numpy in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (1.17.4)
Requirement already satisfied: tqdm in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (4.36.1)
Requirement already satisfied: tensorflow-metadata in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (0.14.0)
Requirement already satisfied: psutil in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (5.6.7)
Requirement already satisfied: requests>=2.19.0 in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (2.22.0)
Requirement already satisfied: attrs in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (19.3.0)
Requirement already satisfied: absl-py in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (0.8.1)
Requirement already satisfied: promise in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (2.2.1)
Requirement already satisfied: future in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (0.18.2)
Requirement already satisfied: termcolor in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (1.1.0)
Requirement already satisfied: dill in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (0.3.1.1)
Requirement already satisfied: setuptools in /opt/conda/lib/python3.7/site-packages (from protobuf>=3.6.1->tensorflow-datasets) (41.4.0)
Requirement already satisfied: googleapis-common-protos in /opt/conda/lib/python3.7/site-packages (from tensorflow-metadata->tensorflow-datasets) (1.6.0)
Requirement already satisfied: idna<2.9,>=2.5 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tensorflow-datasets) (2.8)
Requirement already satisfied: certifi>=2017.4.17 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tensorflow-datasets) (2019.11.28)
Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tensorflow-datasets) (1.24.2)
Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tensorflow-datasets) (3.0.4)
Note: you may need to restart the kernel to use updated packages.
Collecting tfds-nightly
  Downloading https://files.pythonhosted.org/packages/87/88/c4b769a2f56eff26cd3f12d104c7ba7d0e41c9917d442f68668b3e1bf463/tfds_nightly-4.6.0.dev202207040045-py3-none-any.whl (4.4MB)
     |████████████████████████████████| 4.4MB 5.0MB/s eta 0:00:01     |██                              | 286kB 5.0MB/s eta 0:00:01
Collecting toml
  Downloading https://files.pythonhosted.org/packages/44/6f/7120676b6d73228c96e17f1f794d8ab046fc910d781c8d151120c3f1569e/toml-0.10.2-py2.py3-none-any.whl
Requirement already satisfied: promise in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (2.2.1)
Collecting protobuf>=3.12.2
  Downloading https://files.pythonhosted.org/packages/a3/43/c44402da90bf9c2c8f9fe70cc44c66b67cf94ca8e2fadaa0a46a9c6304d3/protobuf-4.21.2-cp37-abi3-manylinux2014_x86_64.whl (407kB)
     |████████████████████████████████| 409kB 37.3MB/s eta 0:00:01
Requirement already satisfied: tqdm in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (4.36.1)
Collecting typing-extensions; python_version < "3.8"
  Downloading https://files.pythonhosted.org/packages/ed/d6/2afc375a8d55b8be879d6b4986d4f69f01115e795e36827fd3a40166028b/typing_extensions-4.3.0-py3-none-any.whl
Requirement already satisfied: tensorflow-metadata in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (0.14.0)
Requirement already satisfied: termcolor in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (1.1.0)
Requirement already satisfied: numpy in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (1.17.4)
Requirement already satisfied: requests>=2.19.0 in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (2.22.0)
Requirement already satisfied: absl-py in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (0.8.1)
Requirement already satisfied: six in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (1.12.0)
Collecting etils[epath]
  Downloading https://files.pythonhosted.org/packages/6b/f0/d717858522d20a4493ea93368a6a737ac7db791e199b07524a41982053f7/etils-0.6.0-py3-none-any.whl (98kB)
     |████████████████████████████████| 102kB 36.2MB/s ta 0:00:01
Collecting importlib-resources; python_version < "3.9"
  Downloading https://files.pythonhosted.org/packages/3c/a7/4e4a2176fed10ab233cc39b083ba4ec222ba52de2be606e3e2b5195264e9/importlib_resources-5.8.0-py3-none-any.whl
Requirement already satisfied: dill in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (0.3.1.1)
Requirement already satisfied: googleapis-common-protos in /opt/conda/lib/python3.7/site-packages (from tensorflow-metadata->tfds-nightly) (1.6.0)
Requirement already satisfied: idna<2.9,>=2.5 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tfds-nightly) (2.8)
Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tfds-nightly) (3.0.4)
Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tfds-nightly) (1.24.2)
Requirement already satisfied: certifi>=2017.4.17 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tfds-nightly) (2019.11.28)
Requirement already satisfied: zipp; extra == "epath" in /opt/conda/lib/python3.7/site-packages (from etils[epath]->tfds-nightly) (0.6.0)
Requirement already satisfied: more-itertools in /opt/conda/lib/python3.7/site-packages (from zipp; extra == "epath"->etils[epath]->tfds-nightly) (8.0.2)
ERROR: tensorflow-metadata 0.14.0 has requirement protobuf<4,>=3.7, but you'll have protobuf 4.21.2 which is incompatible.
ERROR: importlib-resources 5.8.0 has requirement zipp>=3.1.0; python_version < "3.10", but you'll have zipp 0.6.0 which is incompatible.
Installing collected packages: toml, protobuf, typing-extensions, importlib-resources, etils, tfds-nightly
  WARNING: The script tfds is installed in '/root/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
Successfully installed etils-0.6.0 importlib-resources-5.8.0 protobuf-4.21.2 tfds-nightly-4.6.0.dev202207040045 toml-0.10.2 typing-extensions-4.3.0
Note: you may need to restart the kernel to use updated packages.
Collecting tensorflow
  Downloading https://files.pythonhosted.org/packages/db/27/6754ced3dfcdc0507c24df31b5daa9acfa6357f083b355081781fa040404/tensorflow-2.9.1-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (511.7MB)
     |█████████████████████████▎      | 404.1MB 31.1MB/s eta 0:00:04     |████████████████████████████████| 511.7MB 42.6MB/s eta 0:00:01     |██████████████████████████▏     | 419.1MB 8.0MB/s eta 0:00:12     |███████████████████████████▎    | 436.6MB 8.0MB/s eta 0:00:10     |███████████████████████████▍    | 438.5MB 8.0MB/s eta 0:00:10     |███████████████████████████▉    | 445.8MB 11.1MB/s eta 0:00:06     |████████████████████████████▏   | 449.9MB 11.1MB/s eta 0:00:06     |████████████████████████████▍   | 453.8MB 11.1MB/s eta 0:00:06     |█████████████████████████████▋  | 473.7MB 11.1MB/s eta 0:00:04     |██████████████████████████████▌ | 487.4MB 42.6MB/s eta 0:00:01
Collecting flatbuffers<2,>=1.12
  Downloading https://files.pythonhosted.org/packages/eb/26/712e578c5f14e26ae3314c39a1bdc4eb2ec2f4ddc89b708cf8e0a0d20423/flatbuffers-1.12-py2.py3-none-any.whl
Collecting numpy>=1.20
  Downloading https://files.pythonhosted.org/packages/6d/ad/ff3b21ebfe79a4d25b4a4f8e5cf9fd44a204adb6b33c09010f566f51027a/numpy-1.21.6-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (15.7MB)
     |████████████████████████████████| 15.7MB 45.0MB/s eta 0:00:01    |███▋                            | 1.8MB 45.0MB/s eta 0:00:01     |█████████████████████████       | 12.3MB 45.0MB/s eta 0:00:01
Collecting keras<2.10.0,>=2.9.0rc0
  Downloading https://files.pythonhosted.org/packages/ff/ff/f25909606aed26981a8bd6d263f89d64a20ca5e5316e6aafb4c75d9ec8ae/keras-2.9.0-py2.py3-none-any.whl (1.6MB)
     |████████████████████████████████| 1.6MB 26.1MB/s eta 0:00:01
Requirement already satisfied, skipping upgrade: opt-einsum>=2.3.2 in /opt/conda/lib/python3.7/site-packages (from tensorflow) (3.1.0)
Collecting absl-py>=1.0.0
  Downloading https://files.pythonhosted.org/packages/11/8d/5fce604f03c8d30aa0d45451e67efe30d23e65eec7bbef9b9d341b86c0ef/absl_py-1.1.0-py3-none-any.whl (123kB)
     |████████████████████████████████| 133kB 61.3MB/s eta 0:00:01
Collecting tensorflow-estimator<2.10.0,>=2.9.0rc0
  Downloading https://files.pythonhosted.org/packages/61/e1/a72ec68403d91ba433018db58859fd4706642aa9d0fb44ff778934fc4c2c/tensorflow_estimator-2.9.0-py2.py3-none-any.whl (438kB)
     |████████████████████████████████| 440kB 18.1MB/s eta 0:00:01
Collecting protobuf<3.20,>=3.9.2
  Downloading https://files.pythonhosted.org/packages/03/6b/12b307892ef5e9f4a1a92f5996922561c453540f5ce22a09038d2486b451/protobuf-3.19.4-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (1.1MB)
     |████████████████████████████████| 1.1MB 31.4MB/s eta 0:00:01
Requirement already satisfied, skipping upgrade: six>=1.12.0 in /opt/conda/lib/python3.7/site-packages (from tensorflow) (1.12.0)
Requirement already satisfied, skipping upgrade: h5py>=2.9.0 in /opt/conda/lib/python3.7/site-packages (from tensorflow) (2.9.0)
Requirement already satisfied, skipping upgrade: google-pasta>=0.1.1 in /opt/conda/lib/python3.7/site-packages (from tensorflow) (0.1.8)
Collecting tensorboard<2.10,>=2.9
  Downloading https://files.pythonhosted.org/packages/ee/0d/23812e6ce63b3d87c39bc9fee83e28c499052fa83fddddd7daea21a6d620/tensorboard-2.9.1-py3-none-any.whl (5.8MB)
     |████████████████████████████████| 5.8MB 16.4MB/s eta 0:00:01    |▌                               | 81kB 36.0MB/s eta 0:00:01
Collecting libclang>=13.0.0
  Downloading https://files.pythonhosted.org/packages/ab/2f/c6f380aec0b064bccbd81141fecba9862b5634c838f13fff727adc84ceb9/libclang-14.0.1-py2.py3-none-manylinux1_x86_64.whl (14.5MB)
     |████████████████████████████████| 14.5MB 55.1MB/s eta 0:00:01     |██████████████████████▊         | 10.3MB 55.1MB/s eta 0:00:01
Collecting grpcio<2.0,>=1.24.3
  Downloading https://files.pythonhosted.org/packages/6e/15/e6f3805d5003b894cce47af918c6419f2b27cec8d48722087005831203b4/grpcio-1.47.0-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (4.5MB)
     |████████████████████████████████| 4.5MB 23.6MB/s eta 0:00:01
Collecting packaging
  Downloading https://files.pythonhosted.org/packages/05/8e/8de486cbd03baba4deef4142bd643a3e7bbe954a784dc1bb17142572d127/packaging-21.3-py3-none-any.whl (40kB)
     |████████████████████████████████| 40kB 47.4MB/s eta 0:00:01
Collecting tensorflow-io-gcs-filesystem>=0.23.1
  Downloading https://files.pythonhosted.org/packages/02/e2/e52124db811cac83d1773efd3c1e456db3aedb7974a5a4c431126bc2da79/tensorflow_io_gcs_filesystem-0.26.0-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (2.4MB)
     |████████████████████████████████| 2.4MB 44.2MB/s eta 0:00:01
Requirement already satisfied, skipping upgrade: setuptools in /opt/conda/lib/python3.7/site-packages (from tensorflow) (41.4.0)
Requirement already satisfied, skipping upgrade: gast<=0.4.0,>=0.2.1 in /opt/conda/lib/python3.7/site-packages (from tensorflow) (0.2.2)
Requirement already satisfied, skipping upgrade: typing-extensions>=3.6.6 in /root/.local/lib/python3.7/site-packages (from tensorflow) (4.3.0)
Requirement already satisfied, skipping upgrade: wrapt>=1.11.0 in /opt/conda/lib/python3.7/site-packages (from tensorflow) (1.11.2)
Collecting keras-preprocessing>=1.1.1
  Downloading https://files.pythonhosted.org/packages/79/4c/7c3275a01e12ef9368a892926ab932b33bb13d55794881e3573482b378a7/Keras_Preprocessing-1.1.2-py2.py3-none-any.whl (42kB)
     |████████████████████████████████| 51kB 53.4MB/s eta 0:00:01
Collecting astunparse>=1.6.0
  Downloading https://files.pythonhosted.org/packages/2b/03/13dde6512ad7b4557eb792fbcf0c653af6076b81e5941d36ec61f7ce6028/astunparse-1.6.3-py2.py3-none-any.whl
Requirement already satisfied, skipping upgrade: termcolor>=1.1.0 in /opt/conda/lib/python3.7/site-packages (from tensorflow) (1.1.0)
Requirement already satisfied, skipping upgrade: markdown>=2.6.8 in /opt/conda/lib/python3.7/site-packages (from tensorboard<2.10,>=2.9->tensorflow) (3.1.1)
Requirement already satisfied, skipping upgrade: wheel>=0.26 in /opt/conda/lib/python3.7/site-packages (from tensorboard<2.10,>=2.9->tensorflow) (0.33.6)
Collecting tensorboard-data-server<0.7.0,>=0.6.0
  Downloading https://files.pythonhosted.org/packages/60/f9/802efd84988bffd9f644c03b6e66fde8e76c3aa33db4279ddd11c5d61f4b/tensorboard_data_server-0.6.1-py3-none-manylinux2010_x86_64.whl (4.9MB)
     |████████████████████████████████| 4.9MB 37.4MB/s eta 0:00:01     |████████▏                       | 1.2MB 37.4MB/s eta 0:00:01
Collecting werkzeug>=1.0.1
  Downloading https://files.pythonhosted.org/packages/c4/44/f50f2d22cdfb6d56c03d1b4cc3cfa03ebee2f21b59a7768f151e43415ba5/Werkzeug-2.1.2-py3-none-any.whl (224kB)
     |████████████████████████████████| 225kB 63.8MB/s eta 0:00:01
Collecting google-auth-oauthlib<0.5,>=0.4.1
  Downloading https://files.pythonhosted.org/packages/b1/0e/0636cc1448a7abc444fb1b3a63655e294e0d2d49092dc3de05241be6d43c/google_auth_oauthlib-0.4.6-py2.py3-none-any.whl
Collecting tensorboard-plugin-wit>=1.6.0
  Downloading https://files.pythonhosted.org/packages/e0/68/e8ecfac5dd594b676c23a7f07ea34c197d7d69b3313afdf8ac1b0a9905a2/tensorboard_plugin_wit-1.8.1-py3-none-any.whl (781kB)
     |████████████████████████████████| 788kB 35.1MB/s eta 0:00:01     |████████████████████████        | 583kB 35.1MB/s eta 0:00:01
Requirement already satisfied, skipping upgrade: requests<3,>=2.21.0 in /opt/conda/lib/python3.7/site-packages (from tensorboard<2.10,>=2.9->tensorflow) (2.22.0)
Collecting google-auth<3,>=1.6.3
  Downloading https://files.pythonhosted.org/packages/42/1f/b3c5d018045df922f75a9acb81041ab0e2dbb37be8f6f354f0d28c01edea/google_auth-2.9.0-py2.py3-none-any.whl (167kB)
     |████████████████████████████████| 174kB 64.4MB/s eta 0:00:01
Requirement already satisfied, skipping upgrade: pyparsing!=3.0.5,>=2.0.2 in /opt/conda/lib/python3.7/site-packages (from packaging->tensorflow) (2.4.6)
Collecting requests-oauthlib>=0.7.0
  Downloading https://files.pythonhosted.org/packages/6f/bb/5deac77a9af870143c684ab46a7934038a53eb4aa975bc0687ed6ca2c610/requests_oauthlib-1.3.1-py2.py3-none-any.whl
Requirement already satisfied, skipping upgrade: idna<2.9,>=2.5 in /opt/conda/lib/python3.7/site-packages (from requests<3,>=2.21.0->tensorboard<2.10,>=2.9->tensorflow) (2.8)
Requirement already satisfied, skipping upgrade: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /opt/conda/lib/python3.7/site-packages (from requests<3,>=2.21.0->tensorboard<2.10,>=2.9->tensorflow) (1.24.2)
Requirement already satisfied, skipping upgrade: chardet<3.1.0,>=3.0.2 in /opt/conda/lib/python3.7/site-packages (from requests<3,>=2.21.0->tensorboard<2.10,>=2.9->tensorflow) (3.0.4)
Requirement already satisfied, skipping upgrade: certifi>=2017.4.17 in /opt/conda/lib/python3.7/site-packages (from requests<3,>=2.21.0->tensorboard<2.10,>=2.9->tensorflow) (2019.11.28)
Collecting pyasn1-modules>=0.2.1
  Downloading https://files.pythonhosted.org/packages/95/de/214830a981892a3e286c3794f41ae67a4495df1108c3da8a9f62159b9a9d/pyasn1_modules-0.2.8-py2.py3-none-any.whl (155kB)
     |████████████████████████████████| 163kB 35.3MB/s eta 0:00:01
Collecting rsa<5,>=3.1.4; python_version >= "3.6"
  Downloading https://files.pythonhosted.org/packages/30/ab/8fd9e88e6fa5ec41afca995938bbefb72195278e0cfc5bd76a4f29b23fb2/rsa-4.8-py3-none-any.whl
Collecting cachetools<6.0,>=2.0.0
  Downloading https://files.pythonhosted.org/packages/68/aa/5fc646cae6e997c3adf3b0a7e257cda75cff21fcba15354dffd67789b7bb/cachetools-5.2.0-py3-none-any.whl
Collecting oauthlib>=3.0.0
  Downloading https://files.pythonhosted.org/packages/1d/46/5ee2475e1b46a26ca0fa10d3c1d479577fde6ee289f8c6aa6d7ec33e31fd/oauthlib-3.2.0-py3-none-any.whl (151kB)
     |████████████████████████████████| 153kB 35.6MB/s eta 0:00:01
Collecting pyasn1<0.5.0,>=0.4.6
  Downloading https://files.pythonhosted.org/packages/62/1e/a94a8d635fa3ce4cfc7f506003548d0a2447ae76fd5ca53932970fe3053f/pyasn1-0.4.8-py2.py3-none-any.whl (77kB)
     |████████████████████████████████| 81kB 51.8MB/s eta 0:00:01
Installing collected packages: flatbuffers, numpy, keras, absl-py, tensorflow-estimator, protobuf, grpcio, tensorboard-data-server, werkzeug, oauthlib, requests-oauthlib, pyasn1, pyasn1-modules, rsa, cachetools, google-auth, google-auth-oauthlib, tensorboard-plugin-wit, tensorboard, libclang, packaging, tensorflow-io-gcs-filesystem, keras-preprocessing, astunparse, tensorflow
  WARNING: The scripts f2py, f2py3 and f2py3.7 are installed in '/root/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
  Found existing installation: protobuf 4.21.2
    Uninstalling protobuf-4.21.2:
      Successfully uninstalled protobuf-4.21.2
  WARNING: The scripts pyrsa-decrypt, pyrsa-encrypt, pyrsa-keygen, pyrsa-priv2pub, pyrsa-sign and pyrsa-verify are installed in '/root/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
  WARNING: The script google-oauthlib-tool is installed in '/root/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
  WARNING: The script tensorboard is installed in '/root/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
  WARNING: The scripts estimator_ckpt_converter, import_pb_to_tensorboard, saved_model_cli, tensorboard, tf_upgrade_v2, tflite_convert, toco and toco_from_protos are installed in '/root/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
Successfully installed absl-py-1.1.0 astunparse-1.6.3 cachetools-5.2.0 flatbuffers-1.12 google-auth-2.9.0 google-auth-oauthlib-0.4.6 grpcio-1.47.0 keras-2.9.0 keras-preprocessing-1.1.2 libclang-14.0.1 numpy-1.21.6 oauthlib-3.2.0 packaging-21.3 protobuf-3.19.4 pyasn1-0.4.8 pyasn1-modules-0.2.8 requests-oauthlib-1.3.1 rsa-4.8 tensorboard-2.9.1 tensorboard-data-server-0.6.1 tensorboard-plugin-wit-1.8.1 tensorflow-2.9.1 tensorflow-estimator-2.9.0 tensorflow-io-gcs-filesystem-0.26.0 werkzeug-2.1.2
Note: you may need to restart the kernel to use updated packages.
Collecting pandas
  Downloading https://files.pythonhosted.org/packages/3e/0c/23764c4635dcb0a784a787498d56847b90ebf974e65f4ab4053a5d97b1a5/pandas-1.3.5-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (11.3MB)
     |████████████████████████████████| 11.3MB 4.6MB/s eta 0:00:01
Requirement already satisfied, skipping upgrade: numpy>=1.17.3; platform_machine != "aarch64" and platform_machine != "arm64" and python_version < "3.10" in /root/.local/lib/python3.7/site-packages (from pandas) (1.21.6)
Requirement already satisfied, skipping upgrade: python-dateutil>=2.7.3 in /opt/conda/lib/python3.7/site-packages (from pandas) (2.8.1)
Requirement already satisfied, skipping upgrade: pytz>=2017.3 in /opt/conda/lib/python3.7/site-packages (from pandas) (2019.3)
Requirement already satisfied, skipping upgrade: six>=1.5 in /opt/conda/lib/python3.7/site-packages (from python-dateutil>=2.7.3->pandas) (1.12.0)
Installing collected packages: pandas
Successfully installed pandas-1.3.5
Note: you may need to restart the kernel to use updated packages.
In [5]:
%pip install tensorflow-datasets
%pip install tfds-nightly
%pip install --upgrade tensorflow
Requirement already satisfied: tensorflow-datasets in c:\users\nishamol sivan\appdata\roaming\python\python37\site-packages (4.6.0)
Requirement already satisfied: promise in c:\users\nishamol sivan\appdata\roaming\python\python37\site-packages (from tensorflow-datasets) (2.3)
Requirement already satisfied: toml in c:\users\nishamol sivan\appdata\roaming\python\python37\site-packages (from tensorflow-datasets) (0.10.2)
Requirement already satisfied: termcolor in d:\anaconda3\lib\site-packages (from tensorflow-datasets) (1.1.0)
Requirement already satisfied: dill in c:\users\nishamol sivan\appdata\roaming\python\python37\site-packages (from tensorflow-datasets) (0.3.5.1)
Requirement already satisfied: protobuf>=3.12.2 in c:\users\nishamol sivan\appdata\roaming\python\python37\site-packages (from tensorflow-datasets) (3.19.4)
Requirement already satisfied: absl-py in c:\users\nishamol sivan\appdata\roaming\python\python37\site-packages (from tensorflow-datasets) (1.1.0)
Requirement already satisfied: tensorflow-metadata in c:\users\nishamol sivan\appdata\roaming\python\python37\site-packages (from tensorflow-datasets) (1.9.0)
Requirement already satisfied: etils[epath] in c:\users\nishamol sivan\appdata\roaming\python\python37\site-packages (from tensorflow-datasets) (0.6.0)
Requirement already satisfied: requests>=2.19.0 in d:\anaconda3\lib\site-packages (from tensorflow-datasets) (2.23.0)
Requirement already satisfied: tqdm in d:\anaconda3\lib\site-packages (from tensorflow-datasets) (4.43.0)
Note: you may need to restart the kernel to use updated packages.Requirement already satisfied: numpy in c:\users\nishamol sivan\appdata\roaming\python\python37\site-packages (from tensorflow-datasets) (1.21.6)

Requirement already satisfied: typing-extensions; python_version < "3.8" in c:\users\nishamol sivan\appdata\roaming\python\python37\site-packages (from tensorflow-datasets) (4.2.0)
Requirement already satisfied: importlib-resources; python_version < "3.9" in c:\users\nishamol sivan\appdata\roaming\python\python37\site-packages (from tensorflow-datasets) (5.8.0)
Requirement already satisfied: six in d:\anaconda3\lib\site-packages (from tensorflow-datasets) (1.14.0)
Requirement already satisfied: googleapis-common-protos<2,>=1.52.0 in c:\users\nishamol sivan\appdata\roaming\python\python37\site-packages (from tensorflow-metadata->tensorflow-datasets) (1.56.3)
Requirement already satisfied: zipp; extra == "epath" in c:\users\nishamol sivan\appdata\roaming\python\python37\site-packages (from etils[epath]->tensorflow-datasets) (3.8.0)
Requirement already satisfied: certifi>=2017.4.17 in d:\anaconda3\lib\site-packages (from requests>=2.19.0->tensorflow-datasets) (2021.10.8)
Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in d:\anaconda3\lib\site-packages (from requests>=2.19.0->tensorflow-datasets) (1.25.11)
Requirement already satisfied: chardet<4,>=3.0.2 in d:\anaconda3\lib\site-packages (from requests>=2.19.0->tensorflow-datasets) (3.0.4)
Requirement already satisfied: idna<3,>=2.5 in d:\anaconda3\lib\site-packages (from requests>=2.19.0->tensorflow-datasets) (2.9)
Requirement already satisfied: tfds-nightly in c:\users\nishamol sivan\appdata\roaming\python\python37\site-packages (4.6.0.dev202206260045)
Requirement already satisfied: numpy in c:\users\nishamol sivan\appdata\roaming\python\python37\site-packages (from tfds-nightly) (1.21.6)
Requirement already satisfied: etils[epath] in c:\users\nishamol sivan\appdata\roaming\python\python37\site-packages (from tfds-nightly) (0.6.0)
Requirement already satisfied: absl-py in c:\users\nishamol sivan\appdata\roaming\python\python37\site-packages (from tfds-nightly) (1.1.0)
Requirement already satisfied: dill in c:\users\nishamol sivan\appdata\roaming\python\python37\site-packages (from tfds-nightly) (0.3.5.1)
Requirement already satisfied: protobuf>=3.12.2 in c:\users\nishamol sivan\appdata\roaming\python\python37\site-packages (from tfds-nightly) (3.19.4)
Requirement already satisfied: six in d:\anaconda3\lib\site-packages (from tfds-nightly) (1.14.0)
Note: you may need to restart the kernel to use updated packages.
Requirement already satisfied: termcolor in d:\anaconda3\lib\site-packages (from tfds-nightly) (1.1.0)
Requirement already satisfied: tensorflow-metadata in c:\users\nishamol sivan\appdata\roaming\python\python37\site-packages (from tfds-nightly) (1.9.0)
Requirement already satisfied: requests>=2.19.0 in d:\anaconda3\lib\site-packages (from tfds-nightly) (2.23.0)
Requirement already satisfied: tqdm in d:\anaconda3\lib\site-packages (from tfds-nightly) (4.43.0)
Requirement already satisfied: toml in c:\users\nishamol sivan\appdata\roaming\python\python37\site-packages (from tfds-nightly) (0.10.2)
Requirement already satisfied: importlib-resources; python_version < "3.9" in c:\users\nishamol sivan\appdata\roaming\python\python37\site-packages (from tfds-nightly) (5.8.0)
Requirement already satisfied: promise in c:\users\nishamol sivan\appdata\roaming\python\python37\site-packages (from tfds-nightly) (2.3)
Requirement already satisfied: typing-extensions; python_version < "3.8" in c:\users\nishamol sivan\appdata\roaming\python\python37\site-packages (from tfds-nightly) (4.2.0)
Requirement already satisfied: zipp; extra == "epath" in c:\users\nishamol sivan\appdata\roaming\python\python37\site-packages (from etils[epath]->tfds-nightly) (3.8.0)
Requirement already satisfied: googleapis-common-protos<2,>=1.52.0 in c:\users\nishamol sivan\appdata\roaming\python\python37\site-packages (from tensorflow-metadata->tfds-nightly) (1.56.3)
Requirement already satisfied: certifi>=2017.4.17 in d:\anaconda3\lib\site-packages (from requests>=2.19.0->tfds-nightly) (2021.10.8)
Requirement already satisfied: idna<3,>=2.5 in d:\anaconda3\lib\site-packages (from requests>=2.19.0->tfds-nightly) (2.9)
Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in d:\anaconda3\lib\site-packages (from requests>=2.19.0->tfds-nightly) (1.25.11)
Requirement already satisfied: chardet<4,>=3.0.2 in d:\anaconda3\lib\site-packages (from requests>=2.19.0->tfds-nightly) (3.0.4)
ERROR: Could not install packages due to an EnvironmentError: [WinError 5] Access is denied: 'd:\\anaconda3\\lib\\site-packages\\~ensorflow\\lite\\experimental\\microfrontend\\python\\ops\\_audio_microfrontend_op.so'
Collecting tensorflowNote: you may need to restart the kernel to use updated packages.


  Downloading tensorflow-2.9.1-cp37-cp37m-win_amd64.whl (444.0 MB)
Consider using the `--user` option or check the permissions.
Requirement already satisfied, skipping upgrade: flatbuffers<2,>=1.12 in c:\users\nishamol sivan\appdata\roaming\python\python37\site-packages (from tensorflow) (1.12)

Requirement already satisfied, skipping upgrade: opt-einsum>=2.3.2 in d:\anaconda3\lib\site-packages (from tensorflow) (3.1.0)
Requirement already satisfied, skipping upgrade: tensorflow-estimator<2.10.0,>=2.9.0rc0 in c:\users\nishamol sivan\appdata\roaming\python\python37\site-packages (from tensorflow) (2.9.0)
Requirement already satisfied, skipping upgrade: wrapt>=1.11.0 in d:\anaconda3\lib\site-packages (from tensorflow) (1.11.2)
Requirement already satisfied, skipping upgrade: protobuf<3.20,>=3.9.2 in c:\users\nishamol sivan\appdata\roaming\python\python37\site-packages (from tensorflow) (3.19.4)
Collecting keras<2.10.0,>=2.9.0rc0
  Downloading keras-2.9.0-py2.py3-none-any.whl (1.6 MB)
Requirement already satisfied, skipping upgrade: keras-preprocessing>=1.1.1 in c:\users\nishamol sivan\appdata\roaming\python\python37\site-packages (from tensorflow) (1.1.2)
Requirement already satisfied, skipping upgrade: numpy>=1.20 in c:\users\nishamol sivan\appdata\roaming\python\python37\site-packages (from tensorflow) (1.21.6)
Requirement already satisfied, skipping upgrade: setuptools in d:\anaconda3\lib\site-packages (from tensorflow) (46.1.1.post20200323)
Requirement already satisfied, skipping upgrade: libclang>=13.0.0 in c:\users\nishamol sivan\appdata\roaming\python\python37\site-packages (from tensorflow) (14.0.1)
Requirement already satisfied, skipping upgrade: google-pasta>=0.1.1 in d:\anaconda3\lib\site-packages (from tensorflow) (0.1.8)
Requirement already satisfied, skipping upgrade: astunparse>=1.6.0 in c:\users\nishamol sivan\appdata\roaming\python\python37\site-packages (from tensorflow) (1.6.3)
Requirement already satisfied, skipping upgrade: six>=1.12.0 in d:\anaconda3\lib\site-packages (from tensorflow) (1.14.0)
Requirement already satisfied, skipping upgrade: absl-py>=1.0.0 in c:\users\nishamol sivan\appdata\roaming\python\python37\site-packages (from tensorflow) (1.1.0)
Requirement already satisfied, skipping upgrade: grpcio<2.0,>=1.24.3 in d:\anaconda3\lib\site-packages (from tensorflow) (1.29.0)
Requirement already satisfied, skipping upgrade: packaging in c:\users\nishamol sivan\appdata\roaming\python\python37\site-packages (from tensorflow) (21.3)
Requirement already satisfied, skipping upgrade: typing-extensions>=3.6.6 in c:\users\nishamol sivan\appdata\roaming\python\python37\site-packages (from tensorflow) (4.2.0)
Requirement already satisfied, skipping upgrade: h5py>=2.9.0 in d:\anaconda3\lib\site-packages (from tensorflow) (2.10.0)
Collecting tensorboard<2.10,>=2.9
  Downloading tensorboard-2.9.1-py3-none-any.whl (5.8 MB)
Requirement already satisfied, skipping upgrade: gast<=0.4.0,>=0.2.1 in d:\anaconda3\lib\site-packages (from tensorflow) (0.2.2)
Collecting tensorflow-io-gcs-filesystem>=0.23.1
  Downloading tensorflow_io_gcs_filesystem-0.26.0-cp37-cp37m-win_amd64.whl (1.5 MB)
Requirement already satisfied, skipping upgrade: termcolor>=1.1.0 in d:\anaconda3\lib\site-packages (from tensorflow) (1.1.0)
Requirement already satisfied, skipping upgrade: wheel<1.0,>=0.23.0 in d:\anaconda3\lib\site-packages (from astunparse>=1.6.0->tensorflow) (0.34.2)
Requirement already satisfied, skipping upgrade: pyparsing!=3.0.5,>=2.0.2 in d:\anaconda3\lib\site-packages (from packaging->tensorflow) (2.4.6)
Requirement already satisfied, skipping upgrade: tensorboard-plugin-wit>=1.6.0 in c:\users\nishamol sivan\appdata\roaming\python\python37\site-packages (from tensorboard<2.10,>=2.9->tensorflow) (1.8.1)
Requirement already satisfied, skipping upgrade: tensorboard-data-server<0.7.0,>=0.6.0 in c:\users\nishamol sivan\appdata\roaming\python\python37\site-packages (from tensorboard<2.10,>=2.9->tensorflow) (0.6.1)
Requirement already satisfied, skipping upgrade: markdown>=2.6.8 in d:\anaconda3\lib\site-packages (from tensorboard<2.10,>=2.9->tensorflow) (3.2.1)
Requirement already satisfied, skipping upgrade: google-auth<3,>=1.6.3 in d:\anaconda3\lib\site-packages (from tensorboard<2.10,>=2.9->tensorflow) (1.11.0)
Requirement already satisfied, skipping upgrade: google-auth-oauthlib<0.5,>=0.4.1 in d:\anaconda3\lib\site-packages (from tensorboard<2.10,>=2.9->tensorflow) (0.4.1)
Requirement already satisfied, skipping upgrade: requests<3,>=2.21.0 in d:\anaconda3\lib\site-packages (from tensorboard<2.10,>=2.9->tensorflow) (2.23.0)
Requirement already satisfied, skipping upgrade: werkzeug>=1.0.1 in c:\users\nishamol sivan\appdata\roaming\python\python37\site-packages (from tensorboard<2.10,>=2.9->tensorflow) (2.1.2)
Requirement already satisfied, skipping upgrade: cachetools<5.0,>=2.0.0 in d:\anaconda3\lib\site-packages (from google-auth<3,>=1.6.3->tensorboard<2.10,>=2.9->tensorflow) (4.0.0)
Requirement already satisfied, skipping upgrade: pyasn1-modules>=0.2.1 in d:\anaconda3\lib\site-packages (from google-auth<3,>=1.6.3->tensorboard<2.10,>=2.9->tensorflow) (0.2.8)
Requirement already satisfied, skipping upgrade: rsa<4.1,>=3.1.4 in d:\anaconda3\lib\site-packages (from google-auth<3,>=1.6.3->tensorboard<2.10,>=2.9->tensorflow) (4.0)
Requirement already satisfied, skipping upgrade: requests-oauthlib>=0.7.0 in d:\anaconda3\lib\site-packages (from google-auth-oauthlib<0.5,>=0.4.1->tensorboard<2.10,>=2.9->tensorflow) (1.3.0)
Requirement already satisfied, skipping upgrade: chardet<4,>=3.0.2 in d:\anaconda3\lib\site-packages (from requests<3,>=2.21.0->tensorboard<2.10,>=2.9->tensorflow) (3.0.4)
Requirement already satisfied, skipping upgrade: idna<3,>=2.5 in d:\anaconda3\lib\site-packages (from requests<3,>=2.21.0->tensorboard<2.10,>=2.9->tensorflow) (2.9)
Requirement already satisfied, skipping upgrade: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in d:\anaconda3\lib\site-packages (from requests<3,>=2.21.0->tensorboard<2.10,>=2.9->tensorflow) (1.25.11)
Requirement already satisfied, skipping upgrade: certifi>=2017.4.17 in d:\anaconda3\lib\site-packages (from requests<3,>=2.21.0->tensorboard<2.10,>=2.9->tensorflow) (2021.10.8)
Requirement already satisfied, skipping upgrade: pyasn1<0.5.0,>=0.4.6 in d:\anaconda3\lib\site-packages (from pyasn1-modules>=0.2.1->google-auth<3,>=1.6.3->tensorboard<2.10,>=2.9->tensorflow) (0.4.8)
Requirement already satisfied, skipping upgrade: oauthlib>=3.0.0 in d:\anaconda3\lib\site-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tensorboard<2.10,>=2.9->tensorflow) (3.1.0)
Installing collected packages: keras, tensorboard, tensorflow-io-gcs-filesystem, tensorflow
  Attempting uninstall: keras
    Found existing installation: Keras 2.3.1
    Uninstalling Keras-2.3.1:
      Successfully uninstalled Keras-2.3.1
  Attempting uninstall: tensorboard
    Found existing installation: tensorboard 2.2.2
    Uninstalling tensorboard-2.2.2:
      Successfully uninstalled tensorboard-2.2.2
  Attempting uninstall: tensorflow
    Found existing installation: tensorflow 2.2.0
    Uninstalling tensorflow-2.2.0:
      Successfully uninstalled tensorflow-2.2.0
In [7]:
%pip install tensorflow_hub
Requirement already satisfied: tensorflow_hub in d:\anaconda3\lib\site-packages (0.12.0)
Requirement already satisfied: numpy>=1.12.0 in c:\users\nishamol sivan\appdata\roaming\python\python37\site-packages (from tensorflow_hub) (1.21.6)
Requirement already satisfied: protobuf>=3.8.0 in c:\users\nishamol sivan\appdata\roaming\python\python37\site-packages (from tensorflow_hub) (3.19.4)
Note: you may need to restart the kernel to use updated packages.

After the above installations have finished be sure to restart the kernel. You can do this by going to Kernel > Restart.

In [1]:
# Import TensorFlow 
import tensorflow as tf
import tensorflow_datasets as tfds
import tensorflow_hub as hub

# Ignore some warnings that are not relevant (you can remove this if you prefer)
import warnings
warnings.filterwarnings('ignore')
In [2]:
# TODO: Make all other necessary imports.
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
In [3]:
# Some other recommended settings:
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
tfds.disable_progress_bar()

Load the Dataset

Here you'll use tensorflow_datasets to load the Oxford Flowers 102 dataset. This dataset has 3 splits: 'train', 'test', and 'validation'. You'll also need to make sure the training data is normalized and resized to 224x224 pixels as required by the pre-trained networks.

The validation and testing sets are used to measure the model's performance on data it hasn't seen yet, but you'll still need to normalize and resize the images to the appropriate size.

In [4]:
# TODO: Load the dataset with TensorFlow Datasets. Hint: use tfds.load()
dataset,dataset_info = tfds.load('OxfordFlowers102', as_supervised = True, with_info=True)
# TODO: Create a training set, a validation set and a test set.
training_set, val_set, test_set = dataset['train'], dataset['validation'], dataset['test']
Downloading and preparing dataset Unknown size (download: Unknown size, generated: Unknown size, total: Unknown size) to ~\tensorflow_datasets\oxford_flowers102\2.1.1...
Dataset oxford_flowers102 downloaded and prepared to ~\tensorflow_datasets\oxford_flowers102\2.1.1. Subsequent calls will reuse this data.

Explore the Dataset

In [5]:
# TODO: Get the number of examples in each set from the dataset info.
num_training_examples  = dataset_info.splits['train'].num_examples
num_val_examples = dataset_info.splits['validation'].num_examples
num_test_examples = dataset_info.splits['test'].num_examples

print('There are {:,} images in the training set'.format(num_training_examples))
print('There are {:,} images in the validation set'.format(num_val_examples))
print('There are {:,} images in the test set'.format(num_test_examples))

# TODO: Get the number of classes in the dataset from the dataset info.

shape_images = dataset_info.features['image'].shape
num_classes = dataset_info.features['label'].num_classes
print('\nThere are {:,} classes in our dataset'.format(num_classes))
print('The images in our dataset have shape:', shape_images)
There are 1,020 images in the training set
There are 1,020 images in the validation set
There are 6,149 images in the test set

There are 102 classes in our dataset
The images in our dataset have shape: (None, None, 3)
In [6]:
# TODO: Print the shape and corresponding label of 3 images in the training set.
for image, label in training_set.take(3):
    print('The images in the training set have:\n\u2022 shape:', image.shape,'\n\u2022 label:', label)
The images in the training set have:
• shape: (500, 667, 3) 
• label: tf.Tensor(72, shape=(), dtype=int64)
The images in the training set have:
• shape: (500, 666, 3) 
• label: tf.Tensor(84, shape=(), dtype=int64)
The images in the training set have:
• shape: (670, 500, 3) 
• label: tf.Tensor(70, shape=(), dtype=int64)
In [7]:
# TODO: Plot 1 image from the training set. 
# Set the title of the plot to the corresponding image label. 
for image, label in training_set.take(1):
    image = image.numpy().squeeze()
    label = label.numpy()

plt.imshow(image, cmap= plt.cm.binary)
plt.colorbar()
plt.show()

print('The label of this image is:', label)
The label of this image is: 72

Label Mapping

You'll also need to load in a mapping from label to category name. You can find this in the file label_map.json. It's a JSON object which you can read in with the json module. This will give you a dictionary mapping the integer coded labels to the actual names of the flowers.

In [8]:
import json
with open('label_map.json', 'r') as f:
    class_names = json.load(f)
In [9]:
# TODO: Plot 1 image from the training set. Set the title 
# of the plot to the corresponding class name. 

for image, label in training_set.take(1):
    image = image.numpy().squeeze()
    label = label.numpy()

plt.imshow(image, cmap= plt.cm.binary)
plt.colorbar()
plt.show()

print('The class name of this image is:', class_names[str(label)])
The class name of this image is: azalea

%pip --no-cache-dir install --upgrade astroid --user

In [ ]:
%pip --no-cache-dir install --upgrade gast==0.2.2 --user

Create Pipeline

In [19]:
# TODO: Create a pipeline for each set.
import os
#os.environ['AUTOGRAPH_VERBOSITY'] = '10'

def normalize(image, label):    
    image = tf.image.resize(image, (224, 224))
    image = image/255.0    
    return image, label

batch_size =64

training_batches = training_set.shuffle(num_training_examples//4).map(normalize).cache().batch(batch_size).prefetch(1)
validation_batches = val_set.shuffle(num_training_examples//4).map(normalize).cache().batch(batch_size).prefetch(1)
testing_batches = test_set.shuffle(num_training_examples//4).map(normalize).cache().batch(batch_size).prefetch(1)
training_batches,validation_batches,testing_batches
WARNING:tensorflow:AutoGraph could not transform <function normalize at 0x000001D3ADCA76A8> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: 'arguments' object has no attribute 'posonlyargs'
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert
WARNING:tensorflow:AutoGraph could not transform <function normalize at 0x000001D3ADCA76A8> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: 'arguments' object has no attribute 'posonlyargs'
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert
WARNING: AutoGraph could not transform <function normalize at 0x000001D3ADCA76A8> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: 'arguments' object has no attribute 'posonlyargs'
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert
Out[19]:
(<PrefetchDataset element_spec=(TensorSpec(shape=(None, 224, 224, 3), dtype=tf.float32, name=None), TensorSpec(shape=(None,), dtype=tf.int64, name=None))>,
 <PrefetchDataset element_spec=(TensorSpec(shape=(None, 224, 224, 3), dtype=tf.float32, name=None), TensorSpec(shape=(None,), dtype=tf.int64, name=None))>,
 <PrefetchDataset element_spec=(TensorSpec(shape=(None, 224, 224, 3), dtype=tf.float32, name=None), TensorSpec(shape=(None,), dtype=tf.int64, name=None))>)

Build and Train the Classifier

Now that the data is ready, it's time to build and train the classifier. You should use the MobileNet pre-trained model from TensorFlow Hub to get the image features. Build and train a new feed-forward classifier using those features.

We're going to leave this part up to you. If you want to talk through it with someone, chat with your fellow students!

Refer to the rubric for guidance on successfully completing this section. Things you'll need to do:

  • Load the MobileNet pre-trained network from TensorFlow Hub.
  • Define a new, untrained feed-forward network as a classifier.
  • Train the classifier.
  • Plot the loss and accuracy values achieved during training for the training and validation set.
  • Save your trained model as a Keras model.

We've left a cell open for you below, but use as many as you need. Our advice is to break the problem up into smaller parts you can run separately. Check that each part is doing what you expect, then move on to the next. You'll likely find that as you work through each part, you'll need to go back and modify your previous code. This is totally normal!

When training make sure you're updating only the weights of the feed-forward network. You should be able to get the validation accuracy above 70% if you build everything right.

Note for Workspace users: One important tip if you're using the workspace to run your code: To avoid having your workspace disconnect during the long-running tasks in this notebook, please read in the earlier page in this lesson called Intro to GPU Workspaces about Keeping Your Session Active. You'll want to include code from the workspace_utils.py module. Also, If your model is over 1 GB when saved as a checkpoint, there might be issues with saving backups in your workspace. If your saved checkpoint is larger than 1 GB (you can open a terminal and check with ls -lh), you should reduce the size of your hidden layers and train again.

In [20]:
# TODO: Build and train your network.

import tensorflow_hub as hub
mobilenet_v2 ="https://tfhub.dev/google/tf2-preview/mobilenet_v2/classification/4"
feature_extractor = hub.KerasLayer(mobilenet_v2, input_shape=(224, 224,3))
feature_extractor.trainable = False   # untrained with new images, extracting pretrained features from mobilenet
tf.random.set_seed(32)
model = tf.keras.Sequential([
        feature_extractor, #set trainable to false
        #tf.keras.layers.Dense(512, activation = 'relu'),
        #tf.keras.layers.Dropout(0.3),
        #tf.keras.layers.Dense(312, activation = 'relu'),
        #tf.keras.layers.Dropout(0.3),
        #tf.keras.layers.Dense(256, activation = 'relu'),
        #tf.keras.layers.Dropout(0.3),      
        tf.keras.layers.Dense(num_classes, activation = 'softmax')  #feedforward network
])


model.summary()

model.compile(optimizer='adam',
                 loss='sparse_categorical_crossentropy',
                 metrics=['accuracy'])

checkpoint = tf.keras.callbacks.ModelCheckpoint("best_model",
                                            save_best_only=True)
epoch = 18
early_stopping = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=3)
model_history = model.fit(training_batches, 
                            epochs = epoch,
                            validation_data=validation_batches,
                            callbacks=[early_stopping]
                            )
Model: "sequential_2"
_________________________________________________________________
 Layer (type)                Output Shape              Param #   
=================================================================
 keras_layer_2 (KerasLayer)  (None, 1001)              3540265   
                                                                 
 dense_8 (Dense)             (None, 102)               102204    
                                                                 
=================================================================
Total params: 3,642,469
Trainable params: 102,204
Non-trainable params: 3,540,265
_________________________________________________________________
Epoch 1/18
WARNING:tensorflow:AutoGraph could not transform <function Model.make_train_function.<locals>.train_function at 0x000001D3B4480400> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: 'arguments' object has no attribute 'posonlyargs'
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert
WARNING:tensorflow:AutoGraph could not transform <function Model.make_train_function.<locals>.train_function at 0x000001D3B4480400> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: 'arguments' object has no attribute 'posonlyargs'
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert
WARNING: AutoGraph could not transform <function Model.make_train_function.<locals>.train_function at 0x000001D3B4480400> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: 'arguments' object has no attribute 'posonlyargs'
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert
16/16 [==============================] - ETA: 0s - loss: 4.6354 - accuracy: 0.0824WARNING:tensorflow:AutoGraph could not transform <function Model.make_test_function.<locals>.test_function at 0x000001D3AB65B488> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: 'arguments' object has no attribute 'posonlyargs'
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert
WARNING:tensorflow:AutoGraph could not transform <function Model.make_test_function.<locals>.test_function at 0x000001D3AB65B488> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: 'arguments' object has no attribute 'posonlyargs'
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert
WARNING: AutoGraph could not transform <function Model.make_test_function.<locals>.test_function at 0x000001D3AB65B488> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: 'arguments' object has no attribute 'posonlyargs'
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert
16/16 [==============================] - 39s 2s/step - loss: 4.6354 - accuracy: 0.0824 - val_loss: 3.3018 - val_accuracy: 0.2745
Epoch 2/18
16/16 [==============================] - 32s 2s/step - loss: 2.0632 - accuracy: 0.5745 - val_loss: 2.0105 - val_accuracy: 0.5490
Epoch 3/18
16/16 [==============================] - 34s 2s/step - loss: 0.9762 - accuracy: 0.8559 - val_loss: 1.4751 - val_accuracy: 0.6618
Epoch 4/18
16/16 [==============================] - 35s 2s/step - loss: 0.5342 - accuracy: 0.9461 - val_loss: 1.2411 - val_accuracy: 0.7196
Epoch 5/18
16/16 [==============================] - 30s 2s/step - loss: 0.3402 - accuracy: 0.9775 - val_loss: 1.1235 - val_accuracy: 0.7422
Epoch 6/18
16/16 [==============================] - 29s 2s/step - loss: 0.2354 - accuracy: 0.9951 - val_loss: 1.0531 - val_accuracy: 0.7588
Epoch 7/18
16/16 [==============================] - 29s 2s/step - loss: 0.1733 - accuracy: 0.9971 - val_loss: 1.0063 - val_accuracy: 0.7706
Epoch 8/18
16/16 [==============================] - 29s 2s/step - loss: 0.1336 - accuracy: 0.9990 - val_loss: 0.9722 - val_accuracy: 0.7735
Epoch 9/18
16/16 [==============================] - 29s 2s/step - loss: 0.1068 - accuracy: 1.0000 - val_loss: 0.9461 - val_accuracy: 0.7745
Epoch 10/18
16/16 [==============================] - 30s 2s/step - loss: 0.0881 - accuracy: 1.0000 - val_loss: 0.9252 - val_accuracy: 0.7824
Epoch 11/18
16/16 [==============================] - 30s 2s/step - loss: 0.0744 - accuracy: 1.0000 - val_loss: 0.9080 - val_accuracy: 0.7843
Epoch 12/18
16/16 [==============================] - 29s 2s/step - loss: 0.0641 - accuracy: 1.0000 - val_loss: 0.8936 - val_accuracy: 0.7873
Epoch 13/18
16/16 [==============================] - 29s 2s/step - loss: 0.0560 - accuracy: 1.0000 - val_loss: 0.8813 - val_accuracy: 0.7892
Epoch 14/18
16/16 [==============================] - 29s 2s/step - loss: 0.0495 - accuracy: 1.0000 - val_loss: 0.8707 - val_accuracy: 0.7912
Epoch 15/18
16/16 [==============================] - 29s 2s/step - loss: 0.0442 - accuracy: 1.0000 - val_loss: 0.8614 - val_accuracy: 0.7912
Epoch 16/18
16/16 [==============================] - 29s 2s/step - loss: 0.0398 - accuracy: 1.0000 - val_loss: 0.8532 - val_accuracy: 0.7922
Epoch 17/18
16/16 [==============================] - 29s 2s/step - loss: 0.0361 - accuracy: 1.0000 - val_loss: 0.8460 - val_accuracy: 0.7922
Epoch 18/18
16/16 [==============================] - 29s 2s/step - loss: 0.0330 - accuracy: 1.0000 - val_loss: 0.8395 - val_accuracy: 0.7931
In [21]:
# TODO: Plot the loss and accuracy values achieved during training for the training and validation set.

import pandas as pd
pd.DataFrame(model_history.history).plot(figsize=(10,8))
plt.grid(True)
plt.gca().set_ylim(0,1)
plt.show()

Testing your Network

It's good practice to test your trained network on test data, images the network has never seen either in training or validation. This will give you a good estimate for the model's performance on completely new images. You should be able to reach around 70% accuracy on the test set if the model has been trained well.

In [22]:
# TODO: Print the loss and accuracy values achieved on the entire test set.
loss, accuracy = model.evaluate(testing_batches)

print('\nLoss on the TEST Set: {:,.3f}'.format(loss))
print('Accuracy on the TEST Set: {:.3%}'.format(accuracy))
97/97 [==============================] - 95s 969ms/step - loss: 0.9467 - accuracy: 0.7601

Loss on the TEST Set: 0.947
Accuracy on the TEST Set: 76.012%

Save the Model

Now that your network is trained, save the model so you can load it later for making inference. In the cell below save your model as a Keras model (i.e. save it as an HDF5 file).

In [23]:
# TODO: Save your trained model as a Keras model.
model.save_weights('best_model')
model.save('my_model.h5')

Load the Keras Model

Load the Keras model you saved above.

In [24]:
# TODO: Load the Keras model
myModel = tf.keras.models.load_model('my_model.h5',custom_objects={'KerasLayer':hub.KerasLayer})
myModel.load_weights('best_model')
Out[24]:
<tensorflow.python.training.tracking.util.CheckpointLoadStatus at 0x1d3ad7b1c18>

Inference for Classification

Now you'll write a function that uses your trained network for inference. Write a function called predict that takes an image, a model, and then returns the top $K$ most likely class labels along with the probabilities. The function call should look like:

probs, classes = predict(image_path, model, top_k)

If top_k=5 the output of the predict function should be something like this:

probs, classes = predict(image_path, model, 5)
print(probs)
print(classes)
> [ 0.01558163  0.01541934  0.01452626  0.01443549  0.01407339]
> ['70', '3', '45', '62', '55']

Your predict function should use PIL to load the image from the given image_path. You can use the Image.open function to load the images. The Image.open() function returns an Image object. You can convert this Image object to a NumPy array by using the np.asarray() function.

The predict function will also need to handle pre-processing the input image such that it can be used by your model. We recommend you write a separate function called process_image that performs the pre-processing. You can then call the process_image function from the predict function.

Image Pre-processing

The process_image function should take in an image (in the form of a NumPy array) and return an image in the form of a NumPy array with shape (224, 224, 3).

First, you should convert your image into a TensorFlow Tensor and then resize it to the appropriate size using tf.image.resize.

Second, the pixel values of the input images are typically encoded as integers in the range 0-255, but the model expects the pixel values to be floats in the range 0-1. Therefore, you'll also need to normalize the pixel values.

Finally, convert your image back to a NumPy array using the .numpy() method.

In [25]:
# TODO: Create the process_image function
def process_image(image):
    image= np.squeeze(image)
    resized_image = tf.image.resize(image, (224, 224))/255.0
    #resized_image =np.reshape(resized_image,(224,224,3))
    return resized_image

To check your process_image function we have provided 4 images in the ./test_images/ folder:

  • cautleya_spicata.jpg
  • hard-leaved_pocket_orchid.jpg
  • orange_dahlia.jpg
  • wild_pansy.jpg

The code below loads one of the above images using PIL and plots the original image alongside the image produced by your process_image function. If your process_image function works, the plotted image should be the correct size.

In [26]:
from PIL import Image

image_path = './test_images/hard-leaved_pocket_orchid.jpg'
im = Image.open(image_path)
test_image = np.asarray(im)

processed_test_image = process_image(test_image)

fig, (ax1, ax2) = plt.subplots(figsize=(10,10), ncols=2)
ax1.imshow(test_image)
ax1.set_title('Original Image')
ax2.imshow(processed_test_image)
ax2.set_title('Processed Image')
plt.tight_layout()
plt.show()

Once you can get images in the correct format, it's time to write the predict function for making inference with your model.

Inference

Remember, the predict function should take an image, a model, and then returns the top $K$ most likely class labels along with the probabilities. The function call should look like:

probs, classes = predict(image_path, model, top_k)

If top_k=5 the output of the predict function should be something like this:

probs, classes = predict(image_path, model, 5)
print(probs)
print(classes)
> [ 0.01558163  0.01541934  0.01452626  0.01443549  0.01407339]
> ['70', '3', '45', '62', '55']

Your predict function should use PIL to load the image from the given image_path. You can use the Image.open function to load the images. The Image.open() function returns an Image object. You can convert this Image object to a NumPy array by using the np.asarray() function.

Note: The image returned by the process_image function is a NumPy array with shape (224, 224, 3) but the model expects the input images to be of shape (1, 224, 224, 3). This extra dimension represents the batch size. We suggest you use the np.expand_dims() function to add the extra dimension.

In [27]:
# TODO: Create the predict function
def predict(image_path,model,top_k):    
    prediction = model.predict(np.expand_dims(image_path, axis=0))
    result_values, result_indices = tf.math.top_k(prediction,top_k)
    classes = [class_names[str(element)] for element in result_indices.numpy()[0]]
    return result_values.numpy()[0], classes

Sanity Check

It's always good to check the predictions made by your model to make sure they are correct. To check your predictions we have provided 4 images in the ./test_images/ folder:

  • cautleya_spicata.jpg
  • hard-leaved_pocket_orchid.jpg
  • orange_dahlia.jpg
  • wild_pansy.jpg

In the cell below use matplotlib to plot the input image alongside the probabilities for the top 5 classes predicted by your model. Plot the probabilities as a bar graph. The plot should look like this:

You can convert from the class integer labels to actual flower names using class_names.

In [28]:
# TODO: Plot the input image along with the top 5 classes
import glob

images = glob.glob('./test_images/*')
print(images)
for img in images:
    test_image = np.array(Image.open(img))
    processed_test_image = process_image(test_image)
    probs, classes = predict(processed_test_image, myModel, 5)
    print("The top 5 class and it's probability for processed image is \n", format(list(zip(probs,classes))))
    fig, (ax1, ax2,ax3) = plt.subplots(figsize=(20,13), ncols=3)
    ax1.imshow(test_image)
    ax1.set_title('Original Image')
    ax2.imshow(processed_test_image)
    ax2.set_title('Processed Image')
    ax3.set_title('Class Probability for Predicted image')
    ax3.barh(classes[::-1], probs[::-1])
    plt.tight_layout()
    plt.show()
['./test_images\\cautleya_spicata.jpg', './test_images\\hard-leaved_pocket_orchid.jpg', './test_images\\orange_dahlia.jpg', './test_images\\wild_pansy.jpg']
WARNING:tensorflow:AutoGraph could not transform <function Model.make_predict_function.<locals>.predict_function at 0x000001D3B7CF4C80> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: 'arguments' object has no attribute 'posonlyargs'
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert
WARNING:tensorflow:AutoGraph could not transform <function Model.make_predict_function.<locals>.predict_function at 0x000001D3B7CF4C80> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: 'arguments' object has no attribute 'posonlyargs'
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert
WARNING: AutoGraph could not transform <function Model.make_predict_function.<locals>.predict_function at 0x000001D3B7CF4C80> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: 'arguments' object has no attribute 'posonlyargs'
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert
1/1 [==============================] - 2s 2s/step
The top 5 class and it's probability for processed image is 
 [(0.9023008, 'pink-yellow dahlia'), (0.046036407, 'bolero deep blue'), (0.012320645, 'globe thistle'), (0.00902345, 'fritillary'), (0.003002489, 'great masterwort')]
1/1 [==============================] - 0s 170ms/step
The top 5 class and it's probability for processed image is 
 [(0.9973961, 'pink primrose'), (0.0016543164, 'toad lily'), (0.00020735129, 'balloon flower'), (0.00011476159, 'ball moss'), (9.972524e-05, 'morning glory')]
1/1 [==============================] - 0s 80ms/step
The top 5 class and it's probability for processed image is 
 [(0.5022565, 'geranium'), (0.25764653, 'sweet pea'), (0.050968617, 'bromelia'), (0.029456044, 'tree poppy'), (0.027547704, 'lenten rose')]
1/1 [==============================] - 0s 80ms/step
The top 5 class and it's probability for processed image is 
 [(0.99731356, 'petunia'), (0.00090928614, 'black-eyed susan'), (0.00032110882, 'love in the mist'), (0.00029724717, 'frangipani'), (0.00025318842, 'californian poppy')]
In [ ]: